var util = require('../../utils/util');
var config = require('../../utils/config');
var db = require('../../utils/db');
var app = getApp();
Page({
  data: {
    bookMsg:{},
    isLoading:true, //是否正在读取数据
    windowWidth:'',
    windowHeight:'',
    isLogin:false
  },
  onLoad:function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    //1.动态获取设备屏幕的高度，然后计算scroll view的高度
    wx.getSystemInfo({
      success:function(res) {
        that.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        });
      }
    });
    let userInfo = wx.getStorageSync('user');
    if (userInfo!=null&&userInfo!=undefined&&userInfo!={}&&userInfo!='') {
      that.setData({
        isLogin:true,
        isLoading:false
      });
    }else {
      that.setData({
        isLogin:false,
        isLoading:false
      });
    }
    db.selectBookInfo(options.id, (res) => {
      var book = res.data.data;
      that.setData({
        bookMsg: book,
        isLoading: true
      });
    });
  },
  borrowBook:function(e) {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    if (userInfo.userId===undefined) {
      app.getUserInfo(function(userInfo) {
        setTimeout(()=>{
          userInfo = wx.getStorageSync('user');
          that.addBook(e.currentTarget.dataset.id, userInfo.userId);
        }, 2000);
      })
    }else {
      that.addBook(e.currentTarget.dataset.id, userInfo.userId);
    }
  },
  addBook:function(id, userId) {
    var options = {
      url: config.clubApi.put,
      method: 'PUT',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        id: id,
        userId: userId
      }
    };
    util.request(options, (res, err) => {
      if (res.statusCode===200) {
        util.showSuccess('加入成功!', config.showSuccessTime, () => {
          wx.navigateTo({
            url: "../bookList/bookList"
          });
        })
      }
    });
  }
})